package com.hutiao.snowhb.wechat.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.hutiao.snowhb.wechat.vo.WxRecvMsg;
import com.hutiao.snowhb.wechat.vo.WxSendMsg;


public final class WxMsgKit {
	
	private static final Map<String, WxRecvMsgParser> recvParserMap = new HashMap<String, WxRecvMsgParser>();
	
	static {
		// 文本消息解析程序
		recvParserMap.put("text", new WxRecvTextMsgParser());
		// 图片消息解析程序
		recvParserMap.put("image", new WxRecvPicMsgParser());
		// 语音消息
		recvParserMap.put("voice", new WxRecvVoiceMsgParser());
		// 视频消息
		recvParserMap.put("video", new WxRecvVideoMsgParser());
		// 地理位置消息解析程序
		recvParserMap.put("location", new WxRecvGeoMsgParser());
		// 链接消息解析程序
		recvParserMap.put("link", new WxRecvLinkMsgParser());
		
		// 事件消息解析程序
		recvParserMap.put("event-subscribe", new WxRecvEventSubscribeParser());
		recvParserMap.put("event-unsubscribe", new WxRecvEventUnsubscribeParser());
		recvParserMap.put("event-scan", new WxRecvEventSubscribeParser());
		recvParserMap.put("event-location", new WxRecvEventGeoParser());
		recvParserMap.put("event-click", new WxRecvEventClickParser());
	}
	
	public static WxRecvMsg parse(InputStream in) throws JDOMException, IOException {
		Document dom = new SAXBuilder().build(in);
		Element msgType = dom.getRootElement().getChild("MsgType");
		Element event = dom.getRootElement().getChild("Event");
		if(null != msgType) {
			String txt = msgType.getText().toLowerCase();
			if (txt.equals("event") && null != event) {
				txt += "-"+event.getText().toLowerCase();
			}
			WxRecvMsgParser parser = recvParserMap.get(txt);
			if(null != parser) {
				return parser.parser(dom);
			} else {
				System.out.println(txt);
			}
		}
		return null;
	}
	
	public static WxRecvMsg parse(String in) throws JDOMException, IOException {
		StringReader sr = new StringReader(in);
		InputSource is = new InputSource(sr);
		Document dom = new SAXBuilder().build(is);
		Element msgType = dom.getRootElement().getChild("MsgType");
		Element event = dom.getRootElement().getChild("Event");
		if(null != msgType) {
			String txt = msgType.getText().toLowerCase();
			if (txt.equals("event") && null != event) {
				txt += "-"+event.getText().toLowerCase();
			}
			WxRecvMsgParser parser = recvParserMap.get(txt);
			if(null != parser) {
				return parser.parser(dom);
			} else {
				System.out.println(txt);
			}
		}
		
		return null;
	}
	
	public static Document parse(WxSendMsg msg) throws JDOMException {
		return msg.toDocument();
	}
}
